package com.ruoyi.service.impl;

import com.ruoyi.domain.common.PageResult;
import com.ruoyi.domain.common.ResponseResult;
import com.ruoyi.domain.common.UserHolder;
import com.ruoyi.domain.entity.Watchlist;
import com.ruoyi.domain.entity.WatchlistStockInfo;
import com.ruoyi.mapper.StockMapper;
import com.ruoyi.mapper.WatchlistMapper;
import com.ruoyi.service.IWatchlistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 自选股Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-13
 */
@Service
public class WatchlistServiceImpl implements IWatchlistService {
    @Autowired
    private WatchlistMapper watchlistMapper;

    @Autowired
    private StockMapper stockMapper;

    /**
     * 查询自选股
     *
     * @param id 自选股主键
     * @return 自选股
     */
    @Override

    public Watchlist selectWatchlistById(Long id) {
        return watchlistMapper.selectWatchlistById(id);
    }

    /**
     * 查询自选股列表
     *
     * @param watchlist 自选股
     * @return 自选股
     */
    @Override
    public List<Watchlist> selectWatchlistList(Watchlist watchlist) {
        return watchlistMapper.selectWatchlistList(watchlist);
    }

    /**
     * 新增自选股
     *
     * @param watchlist 自选股
     * @return 结果
     */
    @Override
    public ResponseResult insertWatchlist(Watchlist watchlist) {
        //检测参数是否上传
        if (watchlist.getUserId() == null)
            return ResponseResult.error("用户ID未上传");
        if (watchlist.getStockCode() == null)
            return ResponseResult.error("股票代码未上传");
        Integer userId = UserHolder.getUserId();
        if (!watchlist.getUserId().equals(Long.valueOf(userId)))
            return ResponseResult.error("用户ID异常");
        //根据上传的股票代码查询股票ID并检验股票代码是否正确
        Integer stockId = stockMapper.getStockIdByCode(watchlist.getStockCode());
        if (stockId == null) {
            return ResponseResult.error("股票代码错误");
        }
        watchlist.setStockId(stockId);
        //检测记录是否存在
        Watchlist temp = new Watchlist();
        temp.setUserId(watchlist.getUserId());
        temp.setStockCode(watchlist.getStockCode());
        List<Watchlist> list = watchlistMapper.selectWatchlistList(temp);
        if (!list.isEmpty()) {
            return ResponseResult.error("该股票已被收藏");
        }
        watchlistMapper.insertWatchlist(watchlist);
        System.out.println("watchlist = " + watchlist);
        return ResponseResult.success(watchlist.getId());
    }

    /**
     * 修改自选股
     *
     * @param watchlist 自选股
     * @return 结果
     */
    @Override
    public ResponseResult updateWatchlist(Watchlist watchlist) {
        //检测参数是否上传
        if (watchlist.getUserId() == null)
            return ResponseResult.error("用户ID未上传");
        if (watchlist.getStockCode() == null)
            return ResponseResult.error("股票代码未上传");
        Integer userId = UserHolder.getUserId();
        if (!watchlist.getUserId().equals(Long.valueOf(userId)))
            return ResponseResult.error("用户ID异常");
        //检测记录是否存在
        Watchlist temp = new Watchlist();
        temp.setUserId(watchlist.getUserId());
        temp.setStockCode(watchlist.getStockCode());
        List<Watchlist> list = watchlistMapper.selectWatchlistList(temp);
        if (list.isEmpty()) {
            return ResponseResult.error("该股票未被收藏，无法修改");
        }
        return ResponseResult.success(watchlistMapper.updateWatchlist(watchlist));
    }

    /**
     * 批量删除自选股
     *
     * @param ids 需要删除的自选股主键
     * @return 结果
     */
    @Transactional//开启事务
    @Override
    public ResponseResult deleteWatchlistByIds(Long[] ids) {
        try {
            int i = watchlistMapper.deleteWatchlistByIds(ids);
            if (i <= 0) {
                return ResponseResult.error("删除失败，股票未被收藏");
            } else {
                return ResponseResult.success(i);
            }
        } catch (Exception e) {
            return ResponseResult.error("删除出错，请检查数据，稍后重试");
        }
    }

    /**
     * 删除自选股信息
     *
     * @param id 自选股主键
     * @return 结果
     */
    @Override
    public ResponseResult deleteWatchlistById(Long id) {
        try {
            int i = watchlistMapper.deleteWatchlistById(id);
            if (i <= 0) {
                return ResponseResult.error("删除失败，股票未被收藏");
            } else {
                return ResponseResult.success(i);
            }
        } catch (Exception e) {
            return ResponseResult.error("删除出错，请检查数据，稍后重试");
        }
    }

    /**
     * 查询用户自选股相关的股票的基本信息
     *
     * @param watchlistStockInfo 查询条件
     * @return 结果
     */
    @Override
    public PageResult<WatchlistStockInfo> selectWatchlistStockInfoPage(WatchlistStockInfo watchlistStockInfo, int pageNo, int pageSize) {
        // 计算偏移量
        int offset = (pageNo - 1) * pageSize;

        // 获取总记录数
        int total = watchlistMapper.countWatchlistStockInfo(watchlistStockInfo);

        // 获取分页数据
        // 使用pageNo 来存储offset,
        watchlistStockInfo.setPageNo(offset);
        watchlistStockInfo.setPageSize(pageSize);
        List<WatchlistStockInfo> list = watchlistMapper.selectWatchlistStockInfoListWithPaging(watchlistStockInfo);

        // 构建分页结果
        PageResult<WatchlistStockInfo> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setRecords(list);

        return pageResult;
    }

    /**
     * 判断股票是否在用户自选股列表中
     *
     * @param userId 用户ID
     * @param stockId 股票ID
     * @return 是否在自选股列表中
     */
    @Override
    public Long isInWatchlist(Long userId, Long stockId) {
        return watchlistMapper.isInWatchlist(userId, stockId);
    }
}
